<!--
 * @Author: 黄达全
 * @Date: 2024-07-29 14:41:01
 * @LastEditTime: 2024-08-21 11:57:19
-->
<script lang="ts" setup>
import type { CouponAddForm, CouponSelectVO } from "@/common/type"
import CouponApi from "@/api/model/coupon"
import drawer from "@/components/drawer.vue"
import { useTable } from "@/hooks/useTable"
import { ref, watch, getCurrentInstance, ComponentInternalInstance } from "vue"
import dayjs from 'dayjs';
import WebSocketClient from "@/api/websocket"
import useElementPlus from "@/hooks/useElementPlus"

const {
    height,
    pageSize,
    total,
    page,
    tableData,
    drawerRef,
    initForm,
    del,
    handleSelectionChange,
    editId,
    isAddMode,
    submitHandle,
    tableRef,
    tableHeight,
    formRules,
    getDataByPage
} = useTable<CouponSelectVO, CouponAddForm>({
    fetchData: (page, pageSize) => CouponApi.page(page, pageSize),
    addItem: (form) => CouponApi.add(form),
    deleteItem: (ids) => CouponApi.delete(ids),
    updateItem: (form) => CouponApi.update(form),
    initForm: {
        name: "",
        type: 0,
        value: 0,
        total: 0,
        used: 0,
        minPrice: 0,
        status: 0,
        order: 0,
        desc: "",
        startTime: "",
        endTime: "",
    },
    formRules: {
        name: [
            { required: true, message: "请输入优惠卷名称", trigger: "blur" }
        ],
        type: [
            { required: true, message: "请选择优惠卷类型", trigger: "blur" }
        ],
        value: [
            { required: true, message: "请输入优惠卷面值", trigger: "blur" }
        ],
        total: [
            { required: true, message: "请输入优惠卷总数", trigger: "blur" }
        ],
        used: [
            { required: true, message: "请输入优惠卷已使用数量", trigger: "blur" }
        ],
        minPrice: [
            { required: true, message: "请输入优惠卷最低消费金额", trigger: "blur" }
        ],
        status: [
            { required: true, message: "请选择优惠卷状态", trigger: "blur" }
        ],
        order: [
            { required: true, message: "请输入优惠卷排序", trigger: "blur" }
        ],
        desc: [
            { required: true, message: "请输入优惠卷描述", trigger: "blur" }
        ],
        startTime: [
            { required: true, message: "请选择优惠卷开始时间", trigger: "blur" }
        ],
        endTime: [
            { required: true, message: "请选择优惠卷结束时间", trigger: "blur" }
        ]
    },
    title: "优惠卷"
})

// 打开公告新增抽屉
const openAddDrawer = () => {
    isAddMode.value = true
    initForm.name = ''
    initForm.order = 0
    initForm.status = 0
    initForm.type = 0
    initForm.value = 0
    initForm.total = 0
    initForm.used = 0
    initForm.minPrice = 0
    initForm.desc = ''
    initForm.startTime = ''
    initForm.endTime = ''
    datePickerTime.value = [initForm.startTime, initForm.endTime]
    drawerRef.value.open()
}

// 打开公告编辑抽屉
const openEditCouponDrawer = (coupon: CouponSelectVO) => {
    isAddMode.value = false
    initForm.name = coupon.name
    initForm.order = coupon.order
    initForm.status = coupon.status
    initForm.type = coupon.type
    initForm.value = coupon.value
    initForm.total = coupon.total
    initForm.used = coupon.used
    initForm.minPrice = coupon.minPrice
    initForm.desc = coupon.desc
    let startTime = dayjs(coupon.startTime, 'YYYY-MM-DD HH:mm:ss')
    let endTime = dayjs(coupon.endTime, 'YYYY-MM-DD HH:mm:ss')
    initForm.startTime = startTime.format('YYYY-MM-DDTHH:mm:ss')
    initForm.endTime = endTime.format('YYYY-MM-DDTHH:mm:ss')
    datePickerTime.value = [startTime.toDate().toString(), endTime.toDate().toString()]
    editId.value = coupon.id
    drawerRef.value.open()
}

const { message } = useElementPlus()
const datePickerTime = ref<string[]>([])
const changeTimeHandle = (e: Date[]) => {
    const [start, end] = e
    initForm.startTime = dayjs(start).format('YYYY-MM-DDTHH:mm:ss');
    initForm.endTime = dayjs(end).format('YYYY-MM-DDTHH:mm:ss');
    if (initForm.status == 0) {
        const isAfter = dayjs().isAfter(dayjs(start)) // 默认毫秒
        if (!isAfter) return
        message({
            message: '起始时间不能小于当前时间',
            type: 'warning'
        })
        initForm.startTime = ""
        initForm.endTime = ""
        datePickerTime.value=["",""]
    }
    else if (initForm.status == 1) {
        const isAfter = dayjs().isAfter(dayjs(start))
        const isBefore = dayjs().isBefore(dayjs(end))
        if (!isAfter || !isBefore) {
            message({
                message: '当前时间应当在优惠卷时间范围内',
                type: 'warning'
            })
            initForm.startTime = ""
        initForm.endTime = ""
        datePickerTime.value=["",""]
        }

    }
    else if (initForm.status == 2) {
        const isBefore1 = dayjs().isBefore(dayjs(start))
        const isBefore2 = dayjs().isBefore(dayjs(end))
        if (isBefore1 || isBefore2  ) {
            message({
            message: '结束时间不能大于当前时间',
            type: 'warning'
        })
        initForm.startTime = ""
        initForm.endTime = ""
        datePickerTime.value=["",""]
        }
    }

}

const isCouponMoney = ref<boolean>(false)
watch(() => initForm.type, (newVal) => {
    newVal == 0 ? isCouponMoney.value = true : isCouponMoney.value = false
}, { immediate: true })

const ws = new WebSocketClient("ws://localhost:8080/ws/coupon")
const { proxy } = getCurrentInstance() as ComponentInternalInstance
ws.onMessage((data) => {
    tableData.value = JSON.parse(data).records
})
const sendMessage = () => {
    ws.sendMessage(JSON.stringify({
        action: "getCouponData",
        page: page.value,
        pageSize: pageSize.value
    }))
}
ws.onOpen(() => {
    setInterval(() => {
        sendMessage()
    }, proxy!.$config.WS_INTERVAL)
})


</script>

<template>
    <div class="couponPage">
        <el-card class="card" :body-style="{ height: height + 'px', padding: '10px 10px 0 10px' }">
            <template #header>
                <div class="card-header">
                    <el-button color="var(--primary-theme-color)" icon="el-icon-plus" size="small" type="primary"
                        @click="openAddDrawer">新增优惠卷</el-button>
                    <el-button size="small" type="danger" @click="del" icon="el-icon-delete">批量删除</el-button>
                </div>
            </template>
            <div class="card-body">
                <div class="coupon-table" ref="tableRef">
                    <el-table :data="tableData" style="width:99.5%" stripe @selection-change="handleSelectionChange"
                        :height="tableHeight">
                        <el-table-column type="selection" width="80" align="center" />
                        <el-table-column fixed label="规格名称" width="300" align="center">
                            <template #default="{ row }">
                                <div class="coupon-item"
                                    :class="[row.status == 0 ? 'coupon-item-before' : (row.status == 1 ? 'coupon-item-ing' : 'coupon-item-after')]">
                                    <div>
                                        {{ row.name }}
                                    </div>
                                    <div>
                                        {{ row.startTime }} ~ {{ row.endTime }}
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="status" label="状态" width="100" align="center">
                            <template #default="{ row }">
                                <el-tag type="info" v-if="row.status == 0">未开始</el-tag>
                                <el-tag type="success" v-else-if="row.status == 1">进行中</el-tag>
                                <el-tag type="warning" v-else-if="row.status == 2">已结束</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="type" label="优惠力度" width="130" align="center">
                            <template #default="{ row }">
                                {{ row.type == 0 ? "满减" : "折扣" }}{{ row.value }}{{ row.type == 0 ? "元" : "折" }}
                            </template>
                        </el-table-column>
                        <el-table-column label="发放数量" width="140" align="center">
                            <template #default="{ row }">
                                {{ row.total }}张
                            </template>
                        </el-table-column>
                        <el-table-column prop="used" label="已使用数量" width="140" align="center">
                            <template #default="{ row }">
                                {{ row.used }}张
                            </template>
                        </el-table-column>
                        <el-table-column prop="createManagerName" label="创建者" width="140" align="center" />
                        <el-table-column prop="lastUpdateManagerName" label="更新者" width="140" align="center" />
                        <el-table-column prop="createTime" label="创建时间" width="170" align="center" />
                        <el-table-column prop="updateTime" label="更新时间" width="170" align="center" />


                        <el-table-column fixed="right" label="操作" align="center" width="200">
                            <template #default="{ row }">
                                <el-button type="warning" size="small" @click="openEditCouponDrawer(row)"
                                    icon="el-icon-edit">编辑</el-button>
                                <el-button type="danger" size="small" @click="del(row.id)"
                                    icon="el-icon-delete">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="pagination">
                    <el-pagination size="small" background layout="prev, pager, next" :total="total"
                        :page-size="pageSize" @current-change="getDataByPage" />
                </div>
            </div>
        </el-card>
        <drawer ref="drawerRef" :title="isAddMode ? '新增规格' : '修改规格'" direction="rtl" size="35%" @submit="submitHandle">
            <template #rtl>
                <el-form :model="initForm" :rules="formRules" :label-width="100">
                    <el-form-item label="优惠卷名称" prop="title">
                        <el-input v-model="initForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="优惠卷类型">
                        <el-radio-group v-model="initForm.type">
                            <el-radio v-for=" (t, i) in ['固定金额', '百分比折扣']" :key="t" :label="t" :value="i">{{ t
                                }}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item :label="isCouponMoney ? '优惠卷面值' : '优惠卷折扣'">
                        <template v-if="isCouponMoney">
                            <el-input-number style="width: 250px;" v-model="initForm.value" :precision="2"
                                controls-position="right">
                                <template #decrease-icon>
                                    <el-icon>
                                        <el-icon-Minus />
                                    </el-icon>
                                </template>
                                <template #increase-icon>
                                    <el-icon>
                                        <el-icon-Plus />
                                    </el-icon>
                                </template>
                            </el-input-number>
                        </template>
                        <template v-else>
                            <el-input-number :max="10" style="width: 250px;" v-model="initForm.value" :precision="2"
                                controls-position="right">
                                <template #decrease-icon>
                                    <el-icon>
                                        <el-icon-Minus />
                                    </el-icon>
                                </template>
                                <template #increase-icon>
                                    <el-icon>
                                        <el-icon-Plus />
                                    </el-icon>
                                </template>
                            </el-input-number>
                        </template>
                    </el-form-item>

                    <el-form-item label="最低消费标准">
                        <el-input-number style="width: 250px;" v-model="initForm.minPrice" :precision="2"
                            controls-position="right">
                            <template #decrease-icon>
                                <el-icon>
                                    <el-icon-Minus />
                                </el-icon>
                            </template>
                            <template #increase-icon>
                                <el-icon>
                                    <el-icon-Plus />
                                </el-icon>
                            </template>
                        </el-input-number>
                    </el-form-item>
                    <el-form-item label="发放数量">
                        <el-input-number style="width: 250px;" v-model="initForm.total" />
                    </el-form-item>
                    <el-form-item label="已使用数量">
                        <el-input-number style="width: 250px;" v-model="initForm.used" />
                    </el-form-item>

                    <el-form-item label="状态">
                        <el-radio-group v-model="initForm.status">
                            <el-radio v-for=" (t, i) in ['未开始', '进行中', '已结束']" :key="t" :label="t" :value="i">{{ t
                                }}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="有效期">
                        <el-date-picker v-model="datePickerTime" type="datetimerange" range-separator="~"
                            start-placeholder="开始日期" end-placeholder="结束日期" @change="changeTimeHandle" />
                    </el-form-item>
                    <el-form-item label="优惠卷说明">
                        <el-input type="textarea" :rows="12" v-model="initForm.desc"></el-input>
                    </el-form-item>
                    <el-form-item label="排序">
                        <el-input-number style="width: 250px;" v-model="initForm.order"></el-input-number>
                    </el-form-item>
                </el-form>
            </template>
        </drawer>
    </div>
</template>

<style lang="scss" scoped>
.couponPage {
    height: 100%;

    .card-body {
        height: 100%;
        display: flex;
        flex-direction: column;

        .coupon-table {
            flex: 1;
            overflow-y: scroll;

            &::-webkit-scrollbar {
                width: 0;
            }
        }

        .pagination {
            height: 50px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
    }

}

:deep(.el-pagination.is-background .el-pager li.is-active) {
    background-color: var(--primary-theme-color) !important;
    color: #FFFFFF;
}

.coupon-item {
    height: 60px;
    width: 100%;
    border-radius: 5px;
    display: flex;
    flex-direction: column;
    user-select: none;
    cursor: pointer;

    &>div:nth-child(1) {
        font-size: 16px;
        font-weight: bold;
        padding: 5px 10px;
        display: flex;
        justify-content: start;
        width: 100%;
        height: 35px;
    }

    &>div:nth-child(2) {
        font-size: 12px;
        width: 100%;
        display: flex;
        justify-content: center;
        height: 25px;
    }
}

.coupon-item-ing {
    border: 1px dashed var(--el-color-success);
    background-color: rgba(103, 194, 58, 0.1);
}

.coupon-item-before {
    border: 1px dashed var(--el-color-info);
    background-color: rgba(144, 147, 153, 0.1);
}

.coupon-item-after {
    border: 1px dashed var(--el-color-warning);
    background-color: rgba(230, 162, 60, 0.1);
}
</style>
